package com.rivulet.doj_backend.config;

import com.rivulet.doj_backend.config.bean.OnlineUser;
import com.rivulet.doj_backend.pojo.model.admin.UserModel;
import com.rivulet.doj_backend.service.UserService;
import com.rivulet.doj_backend.tools.JvmCacheUtil;
import com.rivulet.doj_backend.tools.common.CommonKey;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Slf4j
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private UserService userService;


    private String getToken(HttpServletRequest request) {
        final String requestHeader = request.getHeader("Authorization");
        if (requestHeader != null && requestHeader.startsWith("rivulet-")) {
            return requestHeader.substring(8);
        }
        /*支持无Bearer 前缀的token*/
        if (requestHeader != null) {
            return requestHeader;
        }
        //如果没有拿到，到参数里面去拿下
        String token = request.getHeader("token");
        if (StringUtils.isNotEmpty(token)) {
            return token;
        }
        return null;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        OnlineUser onlineUser = null;
        try {
            String authToken = getToken(httpServletRequest);
            if(StringUtils.isEmpty(authToken)){
                filterChain.doFilter(httpServletRequest, httpServletResponse);
                return;
            }
            onlineUser = (OnlineUser) JvmCacheUtil.get(CommonKey.userCache,authToken);
            if (onlineUser != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                onlineUser.setAuthToken(authToken);
                UserPrincipal userPrincipal = new UserPrincipal(onlineUser);
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userPrincipal, null, userPrincipal.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
            //没用实际作用，仅增加tv_token全局过滤，方便开发测试功能，后期需删除
            if(authToken.equals("tv_token")){
                UserPrincipal defaultUser = new UserPrincipal(
                        (OnlineUser) new UserModel(
                                1L,
                                "青眼白龙",
                                "4BDDBC41FD88DE6D5018FFEDE53ADB26"
                        )
                );
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(defaultUser, null, defaultUser.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        } catch (Exception e) {
            log.debug("{}", e.getMessage());
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
